<script setup>
import { ref, onMounted } from 'vue'
import { getEmpList, addEmps ,getEmpById,updateEmp,deleteEmp} from '@/api/emp'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryAllApi } from '../../api/dept'

const searchEmp = ref({
  name: '',
  gender: '',
  date: ''
})
//声明token
const token = ref('')
// 员工列表数据
const empList = ref([])
// 分页相关数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取员工列表
const loadEmpList = async () => {
  const params = {
    name: searchEmp.value.name || undefined,
    gender: searchEmp.value.gender || undefined,
    begin: searchEmp.value.date && searchEmp.value.date[0] ? searchEmp.value.date[0] : undefined,
    end: searchEmp.value.date && searchEmp.value.date[1] ? searchEmp.value.date[1] : undefined,
    page: pageNum.value,
    pageSize: pageSize.value
  }

  const result = await getEmpList(params)
  empList.value = result.data.rows
  total.value = result.data.total
}

// 重置员工表单
const resetEmployeeForm = () => {
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  }
  imageUrl.value = ''
}

//新增员工
const addEmp = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增员工'
  // 重置表单数据
  resetEmployeeForm()
  //重置表单验证
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields()
  }
}

// 保存员工信息
const saveEmployee = async () => {
  try {
    // 表单校验
    await employeeFormRef.value.validate()
    
    // 处理工作经历数据
    const employeeData = { ...employee.value }
    employeeData.exprList = employeeData.exprList.map(expr => {
      return {
        begin: expr.dateRange && expr.dateRange[0] ? expr.dateRange[0] : '',
        end: expr.dateRange && expr.dateRange[1] ? expr.dateRange[1] : '',
        company: expr.company,
        job: expr.job
      }
    })
    //判断是否是修改
    let result =null
if(employee.value.id){ 
  result= await updateEmp(employeeData)
  if(result.code){ 
    ElMessage.success('修改成功')
  }else{
    ElMessage.error('修改失败')
  }
}else{ 
  result= await addEmps(employeeData)
  if(result.code){ 
    ElMessage.success('保存成功')
  }else{
    ElMessage.error('保存失败')
  }
}
    // 关闭对话框
    dialogVisible.value = false   
    // 重新加载员工列表
    loadEmpList()
  } catch (error) {
    // 检查是否是表单校验错误
    if (error instanceof Error && error.message) {
      ElMessage.error(error.message)
    } else {
      // 保存失败的提示
      ElMessage.error('保存失败' )
    }
  }
}

//新增/修改表单
const employeeFormRef = ref(null)
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增员工')


//文件上传
const imageUrl = ref('')
// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
  imageUrl.value = response.data;
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}
// 性别显示转换
const formatGender = (gender) => {
  return gender === 1 ? '男' : '女'
}

// 职位显示转换
const formatJob = (job) => {
  const jobMap = {
    1: '班主任',
    2: '讲师',
    3: '学工主管',
    4: '教研主管',
    5: '咨询师'
  }
  return jobMap[job] || '其他'
}
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])

// 职位列表数据
const jobs = ref([{ name: '班主任', value: 1 }, { name: '讲师', value: 2 }, { name: '学工主管', value: 3 }, { name: '教研主管', value: 4 }, { name: '咨询师', value: 5 }])

//部门列表数据
const deptList = ref([])
// 处理查询
const handleSearch = () => {
  // 查询时重置页码为第一页
  pageNum.value = 1
  loadEmpList()
}

// 处理重置
const handleReset = () => {
  searchEmp.value = {
    name: '',
    gender: '',
    date: ''
  }
  handleSearch()
}

// 处理编辑
const handleEdit = async(id) => {
   const result= await getEmpById(id)
if(result.code){ 
//设置弹窗名称
 dialogTitle.value = '修改员工信息'
 //打开弹窗
 dialogVisible.value = true
 //设置员工信息
 employee.value = result.data
 //回显员工经历时间
 employee.value.exprList = result.data.exprList.map(expr => {
  return {
    company: expr.company,
    job: expr.job,
    dateRange: [expr.begin, expr.end]
  }
})
}else{
  ElMessage.error('获取员工信息失败')
}

}

// 处理删除
const handleDelete = (id) => {
  //弹出警告
  ElMessageBox.confirm('此操作将永久删除该员工, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    // 删除员工
    const result = await deleteEmp(id)
    if(result.code){ 
      ElMessage.success('删除成功')
      loadEmpList()
    }else{
      ElMessage.error(result.msg)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const selectedIds = ref([])
//批量删除第一步获取选中的员工id
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map( item => item.id);
}
//批量删除第二步
const handleBatchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的学员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
 if(selectedIds.value && selectedIds.value.length > 0){
      const result = await deleteEmp(selectedIds.value);
      if(result.code){
        ElMessage.success('删除成功');
        loadEmpList();
      }else{
        ElMessage.error(result.msg);
      }
    }else {
      ElMessage.info('您没有选择任何要删除的数据');
    }
  }).catch(() => { //取消
    ElMessage.info('您已取消删除');
  })
}

// 页面大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadEmpList()
}

// 页码改变
const handleCurrentChange = (val) => {
  pageNum.value = val
  loadEmpList()
}

//部门动态绑定
const loadDeptList = async () => {
  const result = await queryAllApi()
  deptList.value = result.data
}
// 页面加载时获取数据
onMounted(() => {
  loadEmpList()
  loadDeptList()
  getToken(); //获取token
})

//获取token
const getToken = () => {
  const loginUser = JSON.parse(localStorage.getItem('loginUser'));
  if(loginUser && loginUser.token){
    token.value = loginUser.token;
  }
}
// 表单校验规则
const rules = {
  username: [
    { required: true, message: '用户名为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2-20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2-10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '性别为必选项', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    { len: 11, message: '手机号应为11位', trigger: 'blur' }
  ]
}

// 添加工作经历
const addExperience = () => {
  employee.value.exprList.push({
    begin: '',
    end: '',
    company: '',
    job: ''
  })
}

// 删除工作经历
const deleteExperience = (index) => {
  employee.value.exprList.splice(index, 1)
}

</script>

<template>
  <h1>员工管理</h1> <br>
  <el-form :inline="true" :model="searchEmp">
    <el-form-item label="姓名">
      <el-input v-model="searchEmp.name" placeholder="请输入员工姓名"></el-input>
    </el-form-item>

    <el-form-item label="性别">
      <el-select v-model="searchEmp.gender" placeholder="请选择">
        <el-option label="男" value="1"></el-option>
        <el-option label="女" value="2"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="入职日期">
      <el-date-picker
        v-model="searchEmp.date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      ></el-date-picker>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>

  <el-button type="primary" @click="addEmp"> + 新增员工</el-button>
  <el-button type="danger" @click="handleBatchDelete"> - 批量删除</el-button>
  <br><br>

  <!-- 员工列表表格 -->
  <el-table :data="empList" border style="width: 100%"@selection-change="handleSelectionChange">
    <!-- 复选框列 -->
    <el-table-column type="selection" width="80" align="center"></el-table-column>
    
    <!-- 姓名列 -->
    <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
    
    <!-- 性别列 -->
    <el-table-column label="性别" width="100" align="center">
      <template #default="scope">
        {{ formatGender(scope.row.gender) }}
      </template>
    </el-table-column>
    
    <!-- 头像列 -->
    <el-table-column label="头像" width="130" align="center">
      <template #default="scope">
        <el-avatar :src="scope.row.image" size="small"></el-avatar>
      </template>
    </el-table-column>
    
    <!-- 部门名称列 -->
    <el-table-column prop="deptName" label="部门名称" width="160" align="center"></el-table-column>
    
    <!-- 职位列 -->
    <el-table-column label="职位" width="180" align="center">
      <template #default="scope">
        {{ formatJob(scope.row.job) }}
      </template>
    </el-table-column>
    
    <!-- 入职日期列 -->
    <el-table-column prop="entryDate" label="入职日期" width="200" align="center"></el-table-column>
    
    <!-- 最后操作时间列 -->
    <el-table-column prop="updateTime" label="最后操作时间"  align="center"></el-table-column>
    
    <!-- 操作列 -->
    <el-table-column fixed="right" label="操作"  align="center">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
    v-model:current-page="pageNum"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20]"
    :total="total"
    layout="total, sizes, prev, pager, next, jumper"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 20px; justify-content: flex-start; display: flex;"
  >
  </el-pagination>

  <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="employeeFormRef" :model="employee" :rules="rules" label-width="80px">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="employee.username" placeholder="请输入员工用户名，2-20个字"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="employee.name" placeholder="请输入员工姓名，2-10个字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="gender in genders" :key="gender.name" :label="gender.name" :value="gender.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位">
              <el-select v-model="employee.job" placeholder="请选择职位" style="width: 100%;">
                <el-option v-for="it in jobs" :key="it.name" :label="it.name" :value="it.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资">
              <el-input v-model="employee.salary" placeholder="请输入员工薪资"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-select v-model="employee.deptId" placeholder="请选择部门" style="width: 100%;">
                <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期">
              <el-date-picker v-model="employee.entryDate" type="date" style="width: 100%;" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :headers="{'token': token}"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 工作经历 -->
        <!-- 第六行 -->
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="工作经历">
              <el-button type="success" size="small" @click="addExperience">+ 添加工作经历</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 动态生成的工作经历列表 -->
        <div v-for="(expr, index) in employee.exprList" :key="index">
          <el-row :gutter="3" style="margin-bottom: 10px;">
            <el-col :span="10">
              <el-form-item size="small" label="时间" label-width="80px">
                <el-date-picker 
                  v-model="expr.dateRange" 
                  type="daterange" 
                  range-separator="至" 
                  start-placeholder="开始日期" 
                  end-placeholder="结束日期" 
                  format="YYYY-MM-DD" 
                  value-format="YYYY-MM-DD"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item size="small" label="公司" label-width="60px">
                <el-input v-model="expr.company" placeholder="请输入公司名称"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item size="small" label="职位" label-width="60px">
                <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="2">
              <el-form-item size="small" label-width="0px">
                <el-button type="danger" @click="deleteExperience(index)">- 删除</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEmployee">保存</el-button>
        </span>
      </template>
    </el-dialog>

</template>

<style scoped>
/* 控制头像大小 */
.el-avatar {
  --el-avatar-size: 40px;
}
.avatar {
  height: 40px;
}
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>